package com.android.Translator.Model.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Handler;
import com.example.provider.Provider;


public class JsonReader {
	
	public static String m_Response = null;
	private static ParseJson m_Parser;

	// [Quan] -- Handler nay dung de nhan tin hieu ket thuc cua
	// qua trinh dich thong qua API va parse json
	public static Handler messageHandler = ModelHandler.TranslateResultHandler; 
	
					
	// [Quan]-- Constructor cua Class JsonReader
	public JsonReader(Activity activity, Provider db, boolean isMyWord, String groupID) {
		m_Parser = new ParseJson(activity, db, isMyWord, groupID);
	}

	// end

	// [Quan] -- ham lay parser
	public ParseJson getJsonParser() {
		return m_Parser;
	}

	// end

	// [Quan] Ham nay thuc hien request len API va lay ket qua tra ve la 1 chuoi
	// Json
	public static String getJsonFromURL(String url, int method,
			List<NameValuePair> params) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse HttpResponse = null;
		HttpEntity entity = null;
		try {
			if (method == ModelConstants.POST) {
				HttpPost post = new HttpPost(url);
				if (params != null)
					post.setEntity(new UrlEncodedFormEntity(params));
				HttpResponse = httpClient.execute(post);
			} else if (method == ModelConstants.GET) {
				if (params != null) {
					String paramString = URLEncodedUtils
							.format(params, "utf-8");
					url += "?" + paramString;
				}
				HttpGet get = new HttpGet(url);
				HttpResponse = httpClient.execute(get);
			}

			entity = HttpResponse.getEntity();
			m_Response = EntityUtils.toString(entity);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return m_Response;
	}

	// end

	
}
